package com.shaoshaohuo.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.CarOption;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.db.DaoUtils;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CarTypeFirst;
import com.shaoshaohuo.app.entity.CarTypeSecond;
import com.shaoshaohuo.app.entity.Order.ShipperUserInfo;
import com.shaoshaohuo.app.entity.OrderDetail;
import com.shaoshaohuo.app.entity.OrderDetailEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.ActivityCollector;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.listener.AuthCheckListener;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.shipper.SelectDriverActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.Location2Util;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.view.InputNumberDialog;
import com.shaoshaohuo.app.view.InputNumberDialog.OnBtClickListener;
import com.shaoshaohuo.app.view.TopbarView;

import java.text.DecimalFormat;
import java.util.List;

/**
 * 货源详情    底部 显示  有三个状态      1. 车主    查看  当前没有报价的货源  显示 下订单
 * 2.  车主    查看 当前已经报价的货源 显示 修改报价 和 取消报价按钮
 * 3.  货主    查看自己发布的货源 显示 已经报价的人数  和查看所有报价的按钮
 */
public class GrabOrderActivity extends BaseActivity implements OnClickListener {

    /**
     * 货主查看自己的  货源详情   要显示 已经报价的人数
     */
    private boolean showNumPrice = false;

    private TopbarView mTopbarView;

    private String orderid;
    private String id;
    private OrderDetail data;

    private TextView tv_order_num;
    private TextView tv_time;
    private ImageView iv_head;
    private TextView tv_name;
    private TextView tv_me_long;
    private TextView tv_pay;
    private TextView tv_start_ad;
    private TextView tv_long;
    private TextView tv_end_ad;
    private TextView tv_goods_name;
    private TextView tv_goods_weghit;
    private TextView tv_car_type;
    private TextView tv_car_long;
    private TextView tv_mark;
    private TextView tv_start_time;
    private TextView tv_end_time;
    private View layout_order_image;
    private ImageView mPhoto1Image;
    private ImageView mPhoto2Image;
    private ImageView mPhoto3Image;
    private Button b_im;
    private Button b_call;

    private Button mQiangButton;

    private LinearLayout ll_already_price;
    private TextView tv_price;
    private Button b_cancel_price;
    private Button b_modify_price;

    private LinearLayout ll_num_price;
    private TextView tv_price_num;
    private Button b_price_num;


    FrameLayout btn_add_order;


    private AlertDialog cancelDialog;

    private String lat;
    private String lng;


    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grab_order);
        orderid = getIntent().getStringExtra(ExtraName.orderid);
        id = getIntent().getStringExtra(ExtraName.id);
        showNumPrice = getIntent().getBooleanExtra(ExtraName.showNumPrice, false);
        lng = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.LNG, "");
        lat = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.LAT, "");
        initView();
        setUpView();
        requestData();


    }


    protected void initView() {
        mTopbarView = (TopbarView) findViewById(R.id.topbar);

        tv_order_num = (TextView) findViewById(R.id.tv_order_num);
        tv_time = (TextView) findViewById(R.id.tv_time);
        iv_head = (ImageView) findViewById(R.id.iv_head);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_me_long = (TextView) findViewById(R.id.tv_me_long);
        tv_pay = (TextView) findViewById(R.id.tv_pay);
        tv_start_ad = (TextView) findViewById(R.id.tv_start_ad);
        tv_long = (TextView) findViewById(R.id.tv_long);
        tv_end_ad = (TextView) findViewById(R.id.tv_end_ad);
        tv_goods_name = (TextView) findViewById(R.id.tv_goods_name);
        tv_goods_weghit = (TextView) findViewById(R.id.tv_goods_weghit);
        tv_car_type = (TextView) findViewById(R.id.tv_car_type);
        tv_car_long = (TextView) findViewById(R.id.tv_car_long);
        tv_mark = (TextView) findViewById(R.id.tv_mark);
        tv_start_time = (TextView) findViewById(R.id.tv_start_time);
        tv_end_time = (TextView) findViewById(R.id.tv_end_time);
        layout_order_image = findViewById(R.id.layout_order_image);
        mPhoto1Image = (ImageView) this.findViewById(R.id.imageview_photo1);
        mPhoto2Image = (ImageView) this.findViewById(R.id.imageview_photo2);
        mPhoto3Image = (ImageView) this.findViewById(R.id.imageview_photo3);
        b_im = (Button) this.findViewById(R.id.b_im);
        b_call = (Button) this.findViewById(R.id.b_call);

        mQiangButton = (Button) this.findViewById(R.id.button_qiang);

        ll_already_price = (LinearLayout) findViewById(R.id.ll_already_price); //
        tv_price = (TextView) findViewById(R.id.tv_price);
        b_cancel_price = (Button) findViewById(R.id.b_cancel_price);
        b_modify_price = (Button) findViewById(R.id.b_modify_price);

        ll_num_price = (LinearLayout) findViewById(R.id.ll_num_price);
        tv_price_num = (TextView) findViewById(R.id.tv_price_num);
        b_price_num = (Button) findViewById(R.id.b_price_num);

        btn_add_order = (FrameLayout) findViewById(R.id.btn_add_order);

        if (showNumPrice) {
            ll_num_price.setVisibility(View.VISIBLE);
            ll_already_price.setVisibility(View.GONE);
            mQiangButton.setVisibility(View.GONE);
        }
    }


    protected void setUpView() {
        mTopbarView.setCenterText("货源详情");
        mTopbarView.setLeftView(true, true);
        mPhoto1Image.setOnClickListener(this);
        mPhoto2Image.setOnClickListener(this);
        mPhoto3Image.setOnClickListener(this);
        mQiangButton.setOnClickListener(this);

        b_im.setOnClickListener(this);
        b_call.setOnClickListener(this);

        b_cancel_price.setOnClickListener(this);
        b_modify_price.setOnClickListener(this);

        b_price_num.setOnClickListener(this);
    }

    protected void requestData() {
        startLoadingDialog();
        RequestService.getInstance().getOrderDetail(this, orderid, OrderDetailEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    OrderDetailEntity entity = (OrderDetailEntity) resultData;
                    updateUi(entity);
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
            }
        });
    }

    protected void updateUi(OrderDetailEntity entity) {
        data = entity.getData();
        if (data == null) {
            showToast("无此订单!");
            finish();
            return;
        }

        tv_order_num.setText("运单号:" + orderid);
        tv_time.setText("下单时间:" + StringHelper.formatDateMinute(data.getCtime()));

        ShipperUserInfo caruserinfo = data.getShipperuserinfo();
        if (caruserinfo != null) {
            ImageLoader.getInstance().displayImage(caruserinfo.getAvatar(), iv_head,
                    ImageLoadUtil.getDisplayImageOptions(R.drawable.pic_head_ad, 180));
            tv_name.setText(caruserinfo.getRealname());
        }

        if (StringUtil.isNumericEmpty(data.getOriginlat()) || StringUtil.isNumericEmpty(data.getOriginlng())
                || StringUtil.isNumericEmpty(lat) || StringUtil.isNumericEmpty(lng)) {
            tv_me_long.setText("距我：- -");
        } else {
            tv_me_long.setText("距我：" + Location2Util.getInstance(this).distance(lat, lng, data.getOriginlat(), data.getOriginlng()) + "km");
        }
        tv_pay.setText(data.getPayment());
        tv_start_ad.setText(AreaUtil.getAreaFullname(data.getOrigincityid()) + data.getOriginaddress());
        if (StringUtil.isNumericEmpty(data.getOriginlat()) || StringUtil.isNumericEmpty(data.getOriginlng())
                || StringUtil.isNumericEmpty(data.getReceivelat()) || StringUtil.isNumericEmpty(data.getReceivelng())) {
            tv_long.setText("里程数：- -");
        } else {
            tv_long.setText("里程数：" + Location2Util.getInstance(this).distance(data.getReceivelat(), data.getReceivelng(),
                    data.getOriginlat(), data.getOriginlng()) + "km");
        }
        tv_end_ad.setText(AreaUtil.getAreaFullname(data.getReceivecityid()) + data.getReceiveaddress());
        tv_goods_name.setText(data.getOrdername());
        if ("1".equals(data.getShipptype())) {
            tv_goods_weghit.setText(CarOption.cargoItems[0]);
        } else if ("2".equals(data.getShipptype())) {
            tv_goods_weghit.setText(data.getShippweight() + "kg");
        } else if ("3".equals(data.getShipptype())) {
            tv_goods_weghit.setText(data.getShipparea() + "m³");
        }
        setCarRequire(data);
        tv_mark.setText(data.getMark());
        tv_start_time.setText(data.getOrigintime());
        tv_end_time.setText(data.getReceivetime());

        String[] shippimg = data.getShippimg();
        if (shippimg.length > 0) {
            layout_order_image.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(shippimg[0], mPhoto1Image, ImageLoadUtil.build);
            if (shippimg.length > 1) {
                ImageLoader.getInstance().displayImage(shippimg[1], mPhoto2Image, ImageLoadUtil.build);
                if (shippimg.length > 2) {
                    ImageLoader.getInstance().displayImage(shippimg[2], mPhoto3Image, ImageLoadUtil.build);
                }
            }
        } else {
            layout_order_image.setVisibility(View.GONE);
        }

        if (showNumPrice) {
            tv_price_num.setText(data.getQiangCount());
        }else{
            if ("1".equals(data.getQiangstatus())) {
//            mQiangButton.setText("已下订单");
//            mQiangButton.setEnabled(false);
                ll_already_price.setVisibility(View.VISIBLE);
                tv_price.setText(data.getTotal());
                mQiangButton.setVisibility(View.GONE);
            } else {
//            mQiangButton.setText("下订单");
//            mQiangButton.setEnabled(true);
                mQiangButton.setVisibility(View.VISIBLE);
                ll_already_price.setVisibility(View.GONE);
            }
        }


        //如果是自己发布的订单，隐藏抢单按钮
        if (AccountManager.getUserId().equals(data.getShipperid())) {
            mQiangButton.setVisibility(View.GONE);
        }


    }


    private void setCarRequire(OrderDetail data) {
        String cartype = data.getCartype();
        String carcid = data.getCarcid();
        int carweight = Integer.parseInt(data.getCarweight());
        int carlength = Integer.parseInt(data.getCarlength());
        if (!TextUtils.isEmpty(cartype) && !TextUtils.isEmpty(carcid)) {
            List<CarTypeFirst> findAllCartype = DaoUtils.findAllCartype();
            CarTypeFirst carTypeFirst = null;
            CarTypeSecond carTypeSecond = null;
            for (CarTypeFirst type : findAllCartype) {
                if (type.getTypeid().equals(cartype)) {
                    carTypeFirst = type;
                    break;
                }
            }
            if (carTypeFirst != null) {
                List<CarTypeSecond> data2 = carTypeFirst.getData();
                for (CarTypeSecond type : data2) {
                    if (carcid.equals(type.getCid())) {
                        carTypeSecond = type;
                        break;
                    }
                }
            }
            if (carTypeSecond != null) {
                tv_car_type.setText(carTypeSecond.getName());
            }
        }
//		if (carweight > 0) {
//			sb.append("/" + CarOption.carWeightItems[carweight - 1]);
//		}
        if (carlength > 0) {
            tv_car_long.setText(CarOption.carLongItems[carlength - 1]);
        }
    }

    public static String formatDouble(String text) {

        String format;
        try {
            DecimalFormat df = new DecimalFormat("0.0");
            double d = Double.parseDouble(text) / 1000;
            if (d <= 0) {
                d = 0;
            }
            format = df.format(d);
            return format;
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_qiang:
                if (AccountManager.isLogin()) {
                    AccountManager.checkCarAuth(this, new AuthCheckListener() {
                        @Override
                        public void authCheckSucceed(String authStatus) {
                            showInputMoneyDialog();
                        }

                        @Override
                        public void authCheckFailured(String errCode, String errDesc) {

                        }
                    });
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.imageview_photo1:
                if (data != null && data.getShippimg().length > 0) {
                    Intent intent = new Intent(this, PhotoBrowseActivity.class);
                    intent.putExtra(ExtraName.photoArray, data.getShippimg());
                    intent.putExtra(ExtraName.photoIndex, 0);
                    startActivity(intent);
                }
                break;
            case R.id.imageview_photo2:
                if (data != null && data.getShippimg().length > 1) {
                    Intent intent = new Intent(this, PhotoBrowseActivity.class);
                    intent.putExtra(ExtraName.photoArray, data.getShippimg());
                    intent.putExtra(ExtraName.photoIndex, 1);
                    startActivity(intent);
                }
                break;
            case R.id.imageview_photo3:
                if (data != null && data.getShippimg().length > 2) {
                    Intent intent = new Intent(this, PhotoBrowseActivity.class);
                    intent.putExtra(ExtraName.photoArray, data.getShippimg());
                    intent.putExtra(ExtraName.photoIndex, 2);
                    startActivity(intent);
                }
            case R.id.b_im:
                IMFactory.openChat(this, data.getShipperid());
                break;
            case R.id.b_call:
                DeviceHelper.callPhone(this, data.getOriginphone());
                break;
            case R.id.b_cancel_price://取消报价
                showCancelDialog();
                break;
            case R.id.b_modify_price://修改价格
                showModifyPriceDialog();
                break;
            case R.id.b_price_num:
                showNumPrice();
                break;
        }
    }

    private void showNumPrice() {
        Intent intent1 = new Intent(this, SelectDriverActivity.class);
        intent1.putExtra(ExtraName.orderid, orderid);
        intent1.putExtra(ExtraName.startCity, AreaUtil.getAreaFullname(data.getOrigincityid()));
        intent1.putExtra(ExtraName.endCity, AreaUtil.getAreaFullname(data.getReceivecityid()));
        intent1.putExtra(ExtraName.cargoType, tv_goods_name.getText().toString());
        startActivity(intent1);
    }

    private void showCancelDialog() {
        if (cancelDialog == null) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("确定取消报价");
            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelDialog.dismiss();
                    cancelPrice();
                }
            });
            builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelDialog.dismiss();
                }
            });
            cancelDialog = builder.create();
        }
        cancelDialog.show();
    }

    private void cancelPrice() {
        startLoadingDialog();
        RequestService.getInstance().cancelPrice(this, id, "1", BaseEntity.class, new RequestListener() {
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    showToast("报价已取消");
                    mQiangButton.setVisibility(View.VISIBLE);
                    ll_already_price.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }


    private void showModifyPriceDialog() {
        InputNumberDialog dialog = new InputNumberDialog(this);
        dialog.setOnBtClickListener(new OnBtClickListener() {

            @Override
            public void onPayClick(double money) {
                // double parseInt = Double.parseDouble(pwd);
                if (money > 0) {
                    moidfyPrice(money);
                } else {
                    showToast("请输入大于0的金额");
                }
            }
        });
        dialog.show();
    }

    private void moidfyPrice(final double money) {
        startLoadingDialog();
        RequestService.getInstance().modifyPrice(this, id, String.valueOf(money), "1", BaseEntity.class, new RequestListener() {
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.getCode() == 1000) {
                    showToast("更改报价成功");
                    tv_price.setText(String.valueOf(money));
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }

    private void showInputMoneyDialog() {
        InputNumberDialog dialog = new InputNumberDialog(this);
        dialog.setOnBtClickListener(new OnBtClickListener() {

            @Override
            public void onPayClick(double money) {
                // double parseInt = Double.parseDouble(pwd);
                if (money > 0) {
                    grabOrder(money);
                } else {
                    showToast("请输入大于0的金额");
                }
            }
        });
        dialog.show();
    }

    private void grabOrder(double money) {
        startLoadingDialog();
        RequestService.getInstance().grabOrder(this, orderid, money + "", BaseEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.getCode() == 1000) {
                    showToast("下单成功");
                    Intent intent = new Intent(GrabOrderActivity.this, OrderDetailActivity.class);
                    intent.putExtra(ExtraName.orderid, orderid);
                    startActivity(intent);
                    finish();
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }


    @Override
    public void finish() {
        if (ActivityCollector.activities.size() == 1) {
            Intent launchIntent = getPackageManager().
                    getLaunchIntentForPackage(getPackageName());
            startActivity(launchIntent);
        }
        super.finish();
    }

}
